package tk.mybatis.springboot.util;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class UDPClient {

    private InetSocketAddress inetSocketAddress;
    private IoSession session;
    private IoConnector connector;

    public UDPClient() {
        super();
    }

    public UDPClient(String host, int port) {
        inetSocketAddress = new InetSocketAddress(host, port);
    }

    public static void main(String[] args) {
        UDPClient udpClient = new UDPClient("127.0.0.1", 9897);
        udpClient.setConnector(new NioDatagramConnector());
        udpClient.getConnector().setHandler(new ClientIoHandler());
        IoConnector connector = udpClient.getConnector();
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(
                new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue())));
        ConnectFuture connectFuture = connector.connect(udpClient.getInetSocketAddress());
        // 等待是否连接成功，相当于是转异步执行为同步执行。
        connectFuture.awaitUninterruptibly();
        // 连接成功后获取会话对象。如果没有上面的等待，由于 connect() 方法是异步的，
        // connectFuture.getSession(), session 可能会无法获取。
        udpClient.setSession(connectFuture.getSession());
        udpClient.getSession().write("Hello, UDPServer!");
    }

    public IoSession getSession() {
        return session;
    }

    public void setSession(IoSession session) {
        this.session = session;
    }

    public IoConnector getConnector() {
        return connector;
    }

    public void setConnector(IoConnector connector) {
        this.connector = connector;
    }

    public InetSocketAddress getInetSocketAddress() {
        return inetSocketAddress;
    }

    public void setInetSocketAddress(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }

}
